
$(function () {

    var size = -1; // 尺码
    var rest = 0; // 库存
    var num = 1; // 数量
    var id = getParamsByUrl(location.href, 'id');

    $.ajax({
        type: 'get',
        url: ajaxUrl('queryProductDetail'),
        data: {
            id: id
        },
        success: function (result) {
            console.log(result);
            if (!result.error) {
                rest = result.num;

                var size = result.size.split("-");
                var start = parseInt(size[0]);
                var end = parseInt(size[1]);

                result.size = [];
                for (var i = start; i <= end; i++) {
                    result.size.push(i);
                }

                $("#detailBox").html(template("detailTpl", {
                    data: result
                }));

                //获得slider插件对象
                var gallery = mui('.mui-slider');
                gallery.slider({
                    interval: 3000 //自动轮播周期，若为0则不自动播放，默认为0；
                });

            } else {
                mui.toast(result.message);
            }
        }
    });

    // 选择尺码
    $('body').on("tap", ".detail-size span", function() {
        $(this).addClass("active").siblings().removeClass("active");
        size = $(this).html();
    });

    // 选择数量
    $("body").on("tap", ".detail-num .reduce", function() {
        num = $(".detail-num .num").val();
        num--;
        if (num < 1) {
            num = 1;
            mui.toast("不能再减了哦");
        }
        $(".detail-num .num").val(num);
    });
    $("body").on("tap", ".detail-num .plus", function() {
        num = $(".detail-num .num").val();
        num++;
        if (num > 99) {
            num = 99;
            mui.toast("不能再加了哦");
        }
        if (num > rest) {
            num = rest;
            mui.toast("不能再加了哦");
        }
        $(".detail-num .num").val(num);
    });

    // 加入购物车
    $("#addCart").on("tap", function() {
        if (size == -1) {
            mui.toast("请选择尺码");
            return;
        }
        $.ajax({
            type: "POST",
            url: ajaxUrl("addCart"),
            data: {
                productId: id,
                num: num,
                size: size
            },
            success: function(result) {
                if (result.error == 400) {
                    mui.toast(result.message);
                    return;
                }
                if (result.success) {
                    // mui.toast("添加购物车成功");
                    mui.confirm("加入购物车成功，跳转到购物车？", "提示", function(message) {
                        console.log(message);
                        if (message.index == 1) {// 确认框
                            window.location.href = "cart.html";
                        }
                    })
                } else {
                    mui.toast(result.message)
                }
            }
        })
    });
})